<template>
  <div class="search">
    <search-header 
      :keyword="searchValue" 
      placeholder="输入影片、影院名称" 
      @search="onSearch" 
      @clear="onSearch" 
    />

    <div v-if="searchFilm.length">
      <van-cell title="影片" />
      <film-card v-for="(film, index) in searchFilm" :key="index" :film="film" />
    </div>

    <div v-else-if="searchCinema.length">
      <van-cell title="影院" />
      <cinema-card v-for="(cinema, index) in searchCinema" :key="index" :cinema="cinema" />
    </div>

    <div v-else>
      <empty 
        v-if="searchValue"
        image-type="search" 
        :show-button="false" 
        :description="'未找到关于 【' + searchValue + '】 的影片或影院'" 
      />
      <div v-show="!searchValue">
        <search-history ref="history" @search="onSearch" />
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import FilmCard from '@/components/FilmCard'
import CinemaCard from '@/components/CinemaCard'
import SearchHeader from './components/SearchHeader'
import SearchHistory from './components/SearchHistory'

export default {
  name: 'Search',
  components: { SearchHeader, FilmCard, CinemaCard, SearchHistory },
  computed: {
    ...mapGetters({
      allFilmList: 'allFilmList',
      cinemaList: 'cinemaList',
    }),
  },
  data() {
    return {
      searchValue: '',
      searchFilm: [],
      searchCinema: []
    }
  },
  created() {
    this.onLoadData()
  },
  methods: {
    async onLoadData() {
      this.$toast.loading('正在加载')
      if (!this.allFilmList.length) {
        await this.getFilmList()
      }
      if (!this.cinemaList.length) {
        const cinemaList = await this.getCinemaList()
        this.getAreaList(cinemaList)
      }
      this.$toast.clear()
    },
    onSearch(searchValue) {
      const searchFilm = this.allFilmList.filter(item => {
        return searchValue && item.name.search(searchValue) > -1
      })
      const searchCinema = this.cinemaList.filter(item => {
        return searchValue && item.cinemaName.search(searchValue) > -1
      })
      if (searchFilm.length || searchCinema.length) {
        this.$refs.history.setWord(searchValue)
      }
      this.searchFilm = searchFilm
      this.searchCinema = searchCinema
      this.searchValue = searchValue
    },
    ...mapActions({
      getFilmList: 'film/getFilmList',
      getCinemaList: 'cinema/getCinemaList',
      getAreaList: 'cinema/getAreaList',
    })
  },
}
</script>